package com.wukang.photovoltaicinspectionpictures.ui.photograph

import android.app.Activity
import android.content.Intent
import androidx.activity.result.contract.ActivityResultContracts
import androidx.lifecycle.viewModelScope
import com.wukang.photovoltaicinspectionpictures.R
import com.wukang.photovoltaicinspectionpictures.base.BaseViewModel
import com.wukang.photovoltaicinspectionpictures.bean.PhotographData
import com.wukang.photovoltaicinspectionpictures.bean.TaskData
import com.wukang.photovoltaicinspectionpictures.ui.UiConstants
import com.wukang.photovoltaicinspectionpictures.ui.shoot.ShootingActivity
import com.wukang.photovoltaicinspectionpictures.ui.shoot.ShootingViewModel
import com.wukang.photovoltaicinspectionpictures.utils.toast
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlin.time.Duration.Companion.seconds

/**
 * 拍照界面ViewModel
 * @author wukang
 */
class TakePhotographViewModel : BaseViewModel() {
    // 拍摄照片类型（是开启照片还是关闭照片）
    private var shootingTypeOpen = false
    private val _switchFragmentState = MutableSharedFlow<Int>()
    private val taskData = TaskData()
    internal var currentPhotographData = PhotographData(openRet = false, closeRet = false)
        private set

    /**
     * 切换fragment界面
     */
    val switchFragmentState: SharedFlow<Int> = _switchFragmentState

    /**
     * 开始拍摄
     */
    fun startShooting(isOpen: Boolean) {
        shootingTypeOpen = isOpen
        useActivity {
            registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
                if (result.resultCode == Activity.RESULT_OK) {
                    result.data?.getStringExtra(ShootingViewModel.KEY_SHOOTING_PHOTO_PATH).takeIf { !it.isNullOrBlank() }?.apply {
                        saveShootingData(this)
                        return@registerForActivityResult
                    }
                }
                R.string.shooting_failure.toast(this@useActivity)
            }.launch(Intent(this, ShootingActivity::class.java))
        }
    }

    /**
     * 更新照片数据
     */
    fun saveShootingData(path: String) {
        if (shootingTypeOpen) {
            currentPhotographData.openRet = true
            currentPhotographData.openPath = path
        } else {
            currentPhotographData.closeRet = true
            currentPhotographData.closePath = path
        }
    }

    /**
     * 发送照片加载中
     */
    fun sendPhotograph() {
        viewModelScope.launch {
            // 切花换到发送照片页
            _switchFragmentState.emit(UiConstants.FRAGMENT_SEND_PHOTOGRAPH)
            // todo..模拟请求
            // 请求拍照结果
            val ret = withContext(Dispatchers.IO) {
                delay(2.seconds)
                return@withContext true
            }
            currentPhotographData.apply {
                this.openRet = ret
                this.closeRet = ret
                this.riskLevel = "中"
                this.photovoltaicLocation = "1号"
            }
            // 切换到照片结果页
            _switchFragmentState.emit(UiConstants.FRAGMENT_PHOTOGRAPH_RESULT)
        }
    }

    /**
     * 清楚数据并重试
     */
    fun clearAndRetry() {
        viewModelScope.launch {
            // 清除缓存照片数据
            currentPhotographData = PhotographData(openRet = false, closeRet = false)
            _switchFragmentState.emit(UiConstants.FRAGMENT_SHOW_PHOTOGRAPH)
        }
    }

    /**
     * 标记地点
     */
    fun markData(mark: String) {
        currentPhotographData.mark = mark
    }

    /**
     * 标记地点并继续拍下一张
     */
    fun markDataAndNext(mark: String) {
        viewModelScope.launch {
            // 保存当前照片数据
            val photographDataList = taskData.photographDataList?.toMutableList() ?: mutableListOf()
            photographDataList.add(currentPhotographData.apply { this.mark = mark })
            taskData.photographDataList = photographDataList
            // 清除缓存照片数据
            currentPhotographData = PhotographData(openRet = false, closeRet = false)
            _switchFragmentState.emit(UiConstants.FRAGMENT_SHOW_PHOTOGRAPH)
        }
    }

    /**
     * 任务完成
     */
    fun taskComplete(taskName: String, powerStationName: String, photographLocation: String) {
        taskData.also {
            it.taskName = taskName
            it.powerStationName = powerStationName
            it.photographLocation = photographLocation
            it.updateTime = System.currentTimeMillis()
        }
        //todo.. saveData

        useActivity { finish() }
    }
}